package com.ljdemo.timemanager.ui.screen.start

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.scaleIn
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.ljdemo.timemanager.config.APPRoute
import com.ljdemo.timemanager.ui.theme.TimeManagerTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext

@OptIn(ExperimentalAnimationApi::class)// 表明使用了实验动画api
@Composable // 此注解表示该方法是用于渲染页面的
fun StartPageView(appNavController: NavHostController?=null) {

    // 线的透明度，by remember设置为响应式，当变量改变时，ui也会改变
    var lineAlpha by remember {
        mutableStateOf(0f)
    }
    // 过渡动画，用在图形上
    val animatable = remember {
        Animatable(0f)
    }

    val circleColor=MaterialTheme.colorScheme.primaryContainer // 圆的颜色，定义在Color.kt中
    val lineColor=MaterialTheme.colorScheme.onPrimaryContainer // 线的颜色

    // 定义控制动画的变量
    // 控制文字动画
    var contentVisible by remember{
        mutableStateOf(false)
    }
    // 控制圆动画
    var iconVisible by remember {
        mutableStateOf(false)
    }
    // 控制线动画
    var showLine by remember {
        mutableStateOf(false)
    }
    val canvasRotation by animateFloatAsState(
        targetValue = if (lineAlpha == 1f) 360f else 0f,
        animationSpec = tween(durationMillis = 1000), // 设置旋转动画时间
        label = ""
    )
    // 开启协程（协程是一种轻量级的线程，可以在代码中进行并发操作，而不会阻塞主线程。）
    LaunchedEffect(Unit){
        // 开启子协程
        withContext(Dispatchers.IO) {
            // 等待500毫秒执行图形的动画
            delay(500)
            iconVisible=true
            delay(500)
            showLine=true
            // 添加过渡动画，会作用于线上
            animatable.animateTo(
                targetValue = 1f,
                animationSpec = tween(
                    durationMillis = 500, //动画时间
                    easing = LinearEasing // 线性过渡
                )
            )
        }
        withContext(Dispatchers.IO){
            // 等待1.5秒
            delay(1500)
            // 修改为true，这个变量是响应式的，值改变时就会触发动画
            contentVisible=true
        }
        delay(1500)
        // 跳转到main_nav
//        appNavController?.navigate(APPRoute.MAIN_NAV)
        appNavController?.navigate(APPRoute.MAIN_NAV){
            // 跳转后从栈中删除该页
            popUpTo(APPRoute.START_SCREEN){
                inclusive=true
            }
        }

    }

    // 向页面写入一个类似于LinearLayout的布局，这个是纵向排列，Raw是横向
    Column(
        modifier = Modifier
            .fillMaxSize()//最大尺寸(填充整个屏幕)
            .background(//设置背景颜色
                MaterialTheme.colorScheme.background
            ),
        verticalArrangement = Arrangement.Center, // 子元素横向居中
        horizontalAlignment = Alignment.CenterHorizontally // 子元素纵向居中
    ) {

        // 定义图形的动画
        AnimatedVisibility(
            visible = iconVisible,
            enter = scaleIn()
        ) {
            // 画板，宽高为100dp
            Canvas(
                modifier = Modifier
                    .size(100.dp)
                    .rotate(canvasRotation) // 设置旋转，canvasRotation的值可以动态变化
            ) {
                // 圆心坐标
                val centerOffset = Offset(size.width/2,size.height/2)
                // 画圆
                drawCircle(
                    color = circleColor,
                    radius = size.minDimension / 2, // 半径为画板大小的一半
                    center = centerOffset
                )
                if (showLine){
                    lineAlpha=animatable.value
                    // 画线
                    drawLine(
                        color = lineColor,
                        start = centerOffset,
                        end = Offset(size.width/2,size.height/2+(size.height/3)),
                        strokeWidth = 3.dp.toPx(),// 粗细
                        cap = StrokeCap.Round, // 圆滑的边角
                        alpha = lineAlpha // 透明度，lineAlpha是动态改变的
                    )
                }
            }
        }

        // 定义文字的动画
        // 当contentVisible为true时，Text组件将以垂直向下展开和淡入的动画效果进入屏幕，初始透明度为0.1f；当contentVisible为false时，Text组件将以相反的动画效果退出屏幕。
        AnimatedVisibility(
            visible = contentVisible,
            enter = expandVertically(expandFrom = Alignment.Bottom)+ fadeIn(
                // 初始透明度
                initialAlpha = 0.1f
            )
        ) {
            // 要执行动画的内容
            Text(
                text = "时间管理大师",
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(15.dp),
                color = MaterialTheme.colorScheme.onPrimaryContainer
            )
        }
    }
}

// 加上后可以在右边预览，不能直接预览动画动画
@Preview(showBackground = true)
@Composable
fun StartPagePreview(){
    TimeManagerTheme {
        // 调用渲染页面的方法
        StartPageView()
    }
}